<template>
  <div>
    <content-wrapper
      :tableList="tableList"
      :searchList="searchList"
      :setting="setting"
      @changeOpt="changeOpt"
      @changeTable="changeTable"
    >
      <div slot="searchLeft">
        <a-button
          type="primary"
          style="margin-right: 20px"
          @click="$commonJs.goPage('authorityNodeAdd')"
          :disabled="!$commonJs.isAth('authorityNodeAdd')"
        >
          <a-icon type="plus" />
          新增
        </a-button>
        <a-button type="primary" style="margin-right: 20px" @click="exportFile">
          <a-icon type="cloud-download" />
          导出
        </a-button>
      </div>
    </content-wrapper>
  </div>
</template>

<script>
import { Modal } from "ant-design-vue";
export default {
  name: "index",
  components: {
    contentWrapper: () => import("@/components/contentWrapper/index")
  },
  data() {
    return {
      tableList: {
        columns: [
          {
            title: "节点名称",
            dataIndex: "text",
            width: 350,
            type: "title",
            scopedSlots: { customRender: "text" }
          },
          {
            title: "节点地址",
            dataIndex: "name"
          },
          {
            title: "唯一字段",
            dataIndex: "unique_key"
          },
          {
            title: "排序",
            dataIndex: "sorts"
          },
          {
            title: "操作",
            dataIndex: "opt",
            width: 120,
            type: "btn",
            list: [
              {
                ath: "editAuthRule",
                label: "编辑",
                extraValue: "authorityNodeEdit",
                className: "text-green divider"
              },
              {
                ath: "delAuthRule",
                label: "删除",
                extraValue: "delete",
                className: "text-danger"
              }
            ],
            scopedSlots: { customRender: "opt" }
          }
        ],
        dataSource: [],
        pagination: {
          current: 1,
          pageSize: 200,
          total: 0,
          pageSizeOptions: ["200"]
        },
        sorter: {}
      },
      searchList: [],
      setting: {}
    };
  },
  methods: {
    changeOpt(item, type) {
      switch (type) {
        case "authorityNodeEdit":
          this.$commonJs.goPage("authorityNodeEdit", item.id);
          break;
        case "delete":
          this.del(item);
      }
    },
    del(item) {
      let that = this;
      Modal.confirm({
        title: "您确定删除该节点吗？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          that.$ajax
            .post(that.$api.delAuthRule, { id: item.id })
            .then(() => {
              that.$notification.success({
                message: "删除成功！"
              });
              that.getInfo();
            })
            .catch(err => {
              that.$notification.error({
                message: err
              });
            });
        }
      });
    },
    changeTable(pagination) {
      Object.assign(this.tableList.pagination, pagination);
      this.getInfo();
    },
    exportFile() {
      let url = this.$api.downloadRuleList;
      url +=
        "&excel_download=1&token=" +
        this.$crypto.getAES(localStorage.getItem("token"));
      const a = document.createElement("a"); // 创建a标签
      a.setAttribute("download", ""); // download属性
      a.setAttribute("href", url); // href链接
      a.click(); // 自执行点击事件
    },
    getInfo() {
      this.$ajax
        .get(this.$api.getAuthRuleList, {
          page_size: 1000,
          page: this.tableList.pagination.current,
          excel_download: "0"
        })
        .then(res => {
          this.tableList.dataSource = this.trans_tree(res.data);
          this.tableList.pagination.total = res.total_count;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    trans_tree(jsonData) {
      //result存储json数据转为树形结构后的结果。
      //temp为临时对象，将json数据按照id值排序.
      //len是json长度，用于循环遍历结束的条件
      var result = [],
        temp = {},
        len = jsonData.length;
      for (var i = 0; i < len; i++) {
        // 以id作为索引存储元素，可以无需遍历直接快速定位元素
        temp[jsonData[i]["id"]] = jsonData[i];
      }
      for (var j = 0; j < len; j++) {
        var currentElement = jsonData[j];
        // 临时变量里面的当前元素的父元素，即pid的值，与找对应id值
        var tempCurrentElementParent = temp[currentElement["pid"]];
        // 如果存在父元素，即如果有pid属性
        if (tempCurrentElementParent) {
          // 如果父元素没有chindren键
          if (!tempCurrentElementParent["children"]) {
            // 设上父元素的children键
            tempCurrentElementParent["children"] = [];
          }
          // 给父元素加上当前元素作为子元素
          tempCurrentElementParent["children"].push(currentElement);
        }
        // 不存在父元素，意味着当前元素是一级元素
        else {
          result.push(currentElement);
        }
      }
      return result;
    }
  },
  beforeRouteUpdate(to, from, next) {
    if (
      to.name === "authorityNode" &&
      (from.name === "authorityNodeAdd" || from.name === "authorityNodeEdit")
    ) {
      this.getInfo();
    }
    next();
  },
  created() {
    this.getInfo();
  }
};
</script>

<style scoped lang="less"></style>
